package com.spring.demo.core.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

import com.spring.demo.core.dao.IFoundDao;
import com.spring.demo.core.service.IFoundService;

/**
 * 金融交易 impl
 * 
 * @author sean
 * 
 */
@Service
public class FoundService implements IFoundService {

	@Autowired
	@Qualifier("jdbcTransactionManager")
	private PlatformTransactionManager transactionManager;

	@Autowired
	@Qualifier("jdbcTransactionTemplate")
	private TransactionTemplate transactionTemplate;

	@Autowired
	private IFoundDao foundDao;

	@Override
	public void doTransforWithTransactionManager(Long fromAccountId,
			Long toAccountId, int balance) {
		TransactionDefinition definition = new DefaultTransactionDefinition();
		TransactionStatus ts = transactionManager.getTransaction(definition);
		try {
			doTransfor(fromAccountId, toAccountId, balance);
			transactionManager.commit(ts);
		} catch (Exception e) {
			transactionManager.rollback(ts);
		}
	}

	@Override
	public void doTransforWithTransactionTemplate(final Long fromAccountId,
			final Long toAccountId, final int balance) {
		transactionTemplate.execute(new TransactionCallbackWithoutResult() {
			@Override
			protected void doInTransactionWithoutResult(TransactionStatus status) {
				try {
					doTransfor(fromAccountId, toAccountId, balance);
				} catch (Exception e) {
					throw new RuntimeException(e);
				}
			}
		});
	}

	private void doTransfor(Long fromAccountId, Long toAccountId, int balance) {
		// 检验balance的有效性
		if (balance <= 0) {
			throw new RuntimeException("balance should be greater than 0!");
		}
		// 检验账户的有效性
		// foundDao.verifyAccount(fromAccountId);
		// foundDao.verifyAccount(toAccountId);

		foundDao.doTransfor(fromAccountId, toAccountId, balance);
	}

	@Override
	public int getAccountBalance(Long accountId) {
		return foundDao.getAccountBalance(accountId);
	}

}
